package com.zhentao.datacontrol.controller;

import com.zhentao.datacontrol.domain.entity.ExecutionLog;
import com.zhentao.datacontrol.service.DataControlExecutionService;
import com.zhentao.subscription.common.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/datacontrol/execution")
@CrossOrigin(origins = "*")
public class DataControlExecutionController {

    @Autowired
    private DataControlExecutionService executionService;

    /**
     * 自动检控 - 执行所有已发布的规则
     */
    @PostMapping("/auto")
    public R<String> executeAutoControl() {
        try {
            String executionId = executionService.executeAutoControl();
            return R.ok(executionId);
        } catch (Exception e) {
            return R.error("自动检控启动失败: " + e.getMessage());
        }
    }

    /**
     * 常规检控 - 执行指定规则
     */
    @PostMapping("/manual")
    public R<String> executeManualControl(@RequestBody List<Long> ruleIds) {
        try {
            if (ruleIds == null || ruleIds.isEmpty()) {
                return R.error("请选择要执行的规则");
            }
            String executionId = executionService.executeManualControl(ruleIds);
            return R.ok(executionId);
        } catch (Exception e) {
            return R.error("常规检控启动失败: " + e.getMessage());
        }
    }

    /**
     * 获取执行历史记录
     */
    @GetMapping("/history")
    public R<List<ExecutionLog>> getExecutionHistory(
            @RequestParam(defaultValue = "1") int pageNo,
            @RequestParam(defaultValue = "20") int pageSize,
            @RequestParam(required = false) String executionType,
            @RequestParam(required = false) String status) {

        try {
            List<ExecutionLog> history = executionService.getExecutionHistory(pageNo, pageSize, executionType, status);
            return R.ok(history);
        } catch (Exception e) {
            // 如果数据库表不存在，返回空列表而不是500错误
            System.err.println("DataControl execution history query failed: " + e.getMessage());
            return R.ok(new java.util.ArrayList<>());
        }
    }

    /**
     * 获取执行详情
     */
    @GetMapping("/detail/{executionId}")
    public R<ExecutionLog> getExecutionDetail(@PathVariable String executionId) {
        ExecutionLog detail = executionService.getExecutionDetail(executionId);
        if (detail == null) {
            return R.error("执行记录不存在");
        }
        return R.ok(detail);
    }

    /**
     * 停止执行
     */
    @PostMapping("/stop/{executionId}")
    public R<Void> stopExecution(@PathVariable String executionId) {
        try {
            boolean success = executionService.stopExecution(executionId);
            return success ? R.ok() : R.error("停止失败");
        } catch (Exception e) {
            return R.error("停止失败: " + e.getMessage());
        }
    }

    /**
     * 重新执行失败的任务
     */
    @PostMapping("/retry/{executionId}")
    public R<String> retryFailedExecution(@PathVariable String executionId) {
        try {
            String newExecutionId = executionService.retryFailedExecution(executionId);
            return R.ok(newExecutionId);
        } catch (Exception e) {
            return R.error("重新执行失败: " + e.getMessage());
        }
    }

    /**
     * 获取执行统计
     */
    @GetMapping("/statistics")
    public R<Map<String, Object>> getExecutionStatistics() {
        Map<String, Object> statistics = executionService.getExecutionStatistics();
        return R.ok(statistics);
    }

    /**
     * 清理历史记录
     */
    @PostMapping("/clean")
    public R<Void> cleanHistory(@RequestParam(defaultValue = "30") int keepDays) {
        try {
            boolean success = executionService.cleanHistory(keepDays);
            return success ? R.ok() : R.error("清理失败");
        } catch (Exception e) {
            return R.error("清理失败: " + e.getMessage());
        }
    }
}
